package android.slc.lib_client;

import android.content.Intent;
import android.slc.rx.SimpleSingleObserver;
import android.slc.rx.SlcRxJavaUtils;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.Utils;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Single;

/**
 * @author slc
 * @date 2023/10/23
 **/
public class EnsureSurviveManager implements Runnable {
    public static final int HEARTBEAT_INTERVAL = 2560;

    public static final EnsureSurviveManager INSTANCE = new EnsureSurviveManager();

    /**
     * 心跳间隔
     */
    private int heartbeatInterval = HEARTBEAT_INTERVAL;
    /**
     * 调试模式
     */
    private boolean debugMode = false;

    private String serverPackageName = "";

    private EnsureSurviveManager() {
    }

    public boolean isDebugMode() {
        return debugMode;
    }

    public void setDebugMode(boolean debugMode) {
        this.debugMode = debugMode;
    }

    public String getServerPackageName() {
        return serverPackageName;
    }

    public void setServerPackageName(String serverPackageName) {
        this.serverPackageName = serverPackageName;
    }

    public void startSurvive() {
        if (StringUtils.isEmpty(serverPackageName)) {
            throw new RuntimeException("请配置服务包名");
        }
        Single.timer(256, TimeUnit.MILLISECONDS).compose(SlcRxJavaUtils.applyOsAndroidSchedulers())
                .subscribe(new SimpleSingleObserver<Long>() {
                    @Override
                    public void onSuccess(@NonNull Long aLong) {
                        super.onSuccess(aLong);
                        run();
                    }
                });
    }

    public void stopSurvive() {
        ThreadUtils.getMainHandler().removeCallbacks(this);
    }

    @Override
    public void run() {
        try {
            if (AppUtils.isAppForeground() || debugMode) {
                Intent intent = new Intent("android.slc.amsdk");
                intent.setPackage(serverPackageName);
                Utils.getApp().sendBroadcast(intent);
            }
        } catch (Exception ignored) {
        } finally {
            ThreadUtils.runOnUiThreadDelayed(this, heartbeatInterval);
        }
    }
}
